package com.dynamic.datasource;

import com.dynamic.datasource.router.DataSourceContext;
import com.dynamic.datasource.support.DataSourceClassResolver;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * @author www
 * @description: 数据源名称获取拦截
 * @date 2022/4/5 21:03
 */
public class AnnotationInterceptor implements MethodInterceptor {

    private final DataSourceClassResolver dataSourceClassResolver;

    public AnnotationInterceptor(Boolean allowedPublicOnly) {
        dataSourceClassResolver = new DataSourceClassResolver(allowedPublicOnly);
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        String dataSourceName = determineDatasourceKey(invocation);
        DataSourceContext.add(dataSourceName);
        try {
            return invocation.proceed();
        } finally {
            DataSourceContext.remove();
        }
    }

    /**
     * 查找数据源名称
     *
     * @param invocation
     * @return
     */
    private String determineDatasourceKey(MethodInvocation invocation) {
        return dataSourceClassResolver.findKey(invocation.getMethod(), invocation.getThis());
    }
}
